package deustotech.mobility.vc.core;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class Gateway {
	public static InetAddress findGatewayAddr() {
		InetAddress gatewayAddr = null;

		try {
			Enumeration ifEnum = NetworkInterface.getNetworkInterfaces();
			boolean found = false;
			if (ifEnum != null) {
				while (ifEnum.hasMoreElements()) {
					NetworkInterface localIf = (NetworkInterface)(ifEnum.nextElement());
					Enumeration ifAddrEnum = localIf.getInetAddresses();
					while (ifAddrEnum.hasMoreElements()) {
						InetAddress ifAddr = (InetAddress)(ifAddrEnum.nextElement());
						byte[] addr = new byte[4];
						addr = ifAddr.getAddress();
						// assume IPv4 address is 'a.b.c.d'
						// mask sign bit in byte and cast to int
						int a = (int) addr[0] & 0xFF;
						int d = (int) addr[3] & 0xFF;
						// d should be 129 or 130 to 254
						if ((a != 127) && (a !=0)) {
							System.out.println("Found gateway Address " + ifAddr.toString());
							Integer in = new Integer(129);
							addr[3] = in.byteValue();
							gatewayAddr = InetAddress.getByAddress(addr);
							found = true;
						}
					}
				}
			}
			if (!found) {
				System.err.println("I couldn't find address of gateway Address");
				byte[] addr = new byte[4];
				addr[0] = (byte) 192; addr[1] = (byte) 168; addr[2] = 0; addr[3] = 1; 
				gatewayAddr = InetAddress.getByAddress(addr);
			}
		} catch (SocketException e2) {
			System.err.println("Error in finding gateway Address");
			e2.printStackTrace();
		} catch (UnknownHostException e) {
			System.err.println("Found gateway Address, but error in creating address");
			e.printStackTrace();
		}

		return gatewayAddr;
	}
}
